﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Kang.Monitor.Wpf.Base;
using Kang.Monitor.Wpf.Models;
using Kang.Monitor.Wpf.Views.ReportViews;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Net.Http.Json;
using System.Reflection;
using System.Text.Json.Serialization;
using System.Windows;
using System.Windows.Controls;
using System.Xml.Linq;
using Page = Kang.Monitor.Wpf.Models.Page;

namespace Kang.Monitor.Wpf.ViewModels
{
    public partial class ReportViewModel : ObservableObject
    {
        public Command MenuChanged { get; }
        public ObservableCollection<ReportMenuModel> ReportMenuList { get; set; }
        public ObservableCollection<CollectData> StressList { get; set; } = new ObservableCollection<CollectData>();
        public List<CollectData> StressListAll = new List<CollectData>();
        private Dictionary<int, string> stateList;

        public Dictionary<int, string> StateList
        {
            get { return stateList; }
            set { SetProperty(ref stateList, value); }
        }

        /// <summary>
        /// 状态
        /// </summary>
        private int selectState;

        public int SelectState
        {
            get { return selectState; }
            set { SetProperty(ref selectState, value); }
        }

        public ReportViewModel()
        {
            SelectState = 0;
            ReportMenuList = new ObservableCollection<ReportMenuModel>();
            ReportMenuList.Add(new ReportMenuModel("压力报表", "Kang.Monitor.Wpf | Kang.Monitor.Wpf.Views.ReportViews.StressView", 1));
            ReportMenuList.Add(new ReportMenuModel("温度报表", "Kang.Monitor.Wpf | Kang.Monitor.Wpf.Views.ReportViews.TemperatureView", 2));
            ReportMenuList.Add(new ReportMenuModel("浓度报表", "Kang.Monitor.Wpf | Kang.Monitor.Wpf.Views.ReportViews.DensityView", 3));

            InitStressList();
            InitStateList();
            this.PageCountList = new List<int> { 10, 20, 50, 100 };

            MenuChanged = new Command(doMenuChanged);
            doMenuChanged(ReportMenuList[0].Url);

            Pager();
        }

        private void InitStateList()
        {
            StateList = new Dictionary<int, string>();
            StateList.Add(0, "全部");
            StateList.Add(1, "异常");
            StateList.Add(2, "正常");
        }

        private Random random = new Random();

        private void InitStressList()
        {
            for (int i = 0; i < 100; i++)
            {
                var temp = random.Next(1, 30);
                StressListAll.Add(new CollectData()
                {
                    Id = i + 1,
                    Value = temp,
                    IsAbnormal = temp > 21,
                    Time = DateTime.Now,
                });
                StressList.Add(new CollectData()
                {
                    Id = i + 1,
                    Value = temp,
                    IsAbnormal = temp > 21,
                    Time = DateTime.Now,
                });
            }
        }

        [RelayCommand]
        private void ReLoad()
        {
            StressList.Clear();
            foreach (var item in StressListAll)
            {
                if (SelectState == 1)
                {
                    if (item.IsAbnormal)
                    {
                        StressList.Add(item);
                    }
                }
                if (SelectState == 2)
                {
                    if (!item.IsAbnormal)
                    {
                        StressList.Add(item);
                    }
                }
                if (SelectState == 0)
                {
                    StressList.Add(item);
                }
            }
        }

        public void doMenuChanged(object arg)
        {
            string[] strValues = arg.ToString().Split('|', StringSplitOptions.RemoveEmptyEntries);
            Assembly assembly = Assembly.LoadFrom(strValues[0].Trim() + ".dll");
            Type type = assembly.GetType(strValues[1].Trim());
            this.ReportContext = (UIElement)Activator.CreateInstance(type);
        }

        private UIElement reportContent;

        public UIElement ReportContext
        {
            get { return reportContent; }
            set { SetProperty(ref reportContent, value); }
        }

        [RelayCommand]
        private void ShowMsg(CollectData obj)
        {
            MessageBox.Show(JsonConvert.SerializeObject(obj));
        }

        [RelayCommand]
        private void ShowMsgFrom(CollectData obj)
        {
            ShowDetail showDetail = new ShowDetail(JsonConvert.SerializeObject(obj));

            bool? result = showDetail.ShowDialog();
            if (result.HasValue)
            {
                if (result.Value)
                {
                    MessageBox.Show(showDetail.Obj);
                    return;
                }
            }

            MessageBox.Show(JsonConvert.SerializeObject(obj));
        }

        private ObservableCollection<Page> pageList;

        public ObservableCollection<Page> PageList
        {
            get { return pageList; }
            set { SetProperty(ref pageList, value); }
        }

        private List<Page> pageAllList = new List<Page>();

        private void InitPage(string name = "1")
        {
            //总共多少条
            TotalCount = StressListAll.Count;
            // 计算总页数
            PageCount = (int)Math.Ceiling(TotalCount / (this.PageCountList[this.CurrentIndex] * 1.0));

            // 若页数<=7，那就全显示
            if (pageCount <= 7)
            {
                PageList = new ObservableCollection<Page>();
                for (int i = 1; i <= pageCount; i++)
                {
                    this.PageList.Add(new Page() { Name = i.ToString() });
                }
            }
            else if (pageCount > 7)
            {
                var minPage = 1;
                var index = -1;
                if (name != "...")
                {
                    int.TryParse(name, out minPage);
                }
                else
                {
                    index = PageList.Select(d => d.Name).ToList().IndexOf("...");
                    if (index > 0)
                    {
                        minPage = int.Parse(PageList[index - 1].Name) + 1;
                    }
                }
                CurrentPage = minPage;
                if (minPage >= 2)
                {
                    minPage = minPage - 2 > 0 ? minPage - 2 : minPage - 1;
                }
                //||                PageList.IndexOf(new Page() { Name = minPage.ToString() }) < 3
                if (pageCount - CurrentPage > 7

                    ||
                    (index == -1 && PageList.Select(d => d.Name).ToList().IndexOf(CurrentPage.ToString()) < 1)

                    )
                {
                    this.PageList = new ObservableCollection<Page>();
                    this.PageList.Add(new Page() { Name = minPage++.ToString() });
                    this.PageList.Add(new Page() { Name = minPage++.ToString() });
                    this.PageList.Add(new Page() { Name = minPage++.ToString() });
                    if (pageCount - minPage == 3)
                    {
                        this.PageList.Add(new Page() { Name = minPage++.ToString() });
                    }
                    else
                    {
                        this.PageList.Add(new Page() { Name = "..." });
                    }
                    this.PageList.Add(new Page() { Name = (pageCount - 2).ToString() });
                    this.PageList.Add(new Page() { Name = (pageCount - 1).ToString() });
                    this.PageList.Add(new Page() { Name = pageCount.ToString() });
                }
                else
                {
                    this.PageList = new ObservableCollection<Page>();
                    this.PageList.Add(new Page() { Name = (pageCount - 6).ToString() });
                    this.PageList.Add(new Page() { Name = (pageCount - 5).ToString() });
                    this.PageList.Add(new Page() { Name = (pageCount - 4).ToString() });
                    this.PageList.Add(new Page() { Name = (pageCount - 3).ToString() });
                    this.PageList.Add(new Page() { Name = (pageCount - 2).ToString() });
                    this.PageList.Add(new Page() { Name = (pageCount - 1).ToString() });
                    this.PageList.Add(new Page() { Name = pageCount.ToString() });
                }
            }
        }

        private List<int> _pageCountList;

        public List<int> PageCountList
        {
            get { return _pageCountList; }
            set { SetProperty(ref _pageCountList, value); }
        }

        private int _startPos;

        public int StartPos
        {
            get { return _startPos; }
            set { SetProperty(ref _startPos, value); }
        }

        private int _endPos;

        public int EndPos
        {
            get { return _endPos; }
            set { SetProperty(ref _endPos, value); }
        }

        private int _totalCount;

        public int TotalCount
        {
            get { return _totalCount; }
            set { SetProperty(ref _totalCount, value); }
        }

        private int _currentPage = 1;

        public int CurrentPage
        {
            get { return _currentPage; }
            set { SetProperty(ref _currentPage, value); }
        }

        /// <summary>
        /// 分页的页码索引
        /// </summary>
        private int _currentIndex;

        public int CurrentIndex
        {
            get { return _currentIndex; }
            set { SetProperty(ref _currentIndex, value); }
        }

        [RelayCommand]
        private void LastPage()
        {
            if (CurrentPage <= 1)
            {
                return;
            }
            CurrentPage--;
            refresh(CurrentPage.ToString());
        }

        [RelayCommand]
        private void NextPage()
        {
            if (PageCount <= CurrentPage)
            {
                return;
            }
            CurrentPage++;
            refresh(CurrentPage.ToString());
        }

        [RelayCommand]
        private void GoPage(string name)
        {
            refresh(name);
        }

        private ObservableCollection<CollectData> _employeeBindingList;

        public ObservableCollection<CollectData> EmployeeBindingList
        {
            get { return _employeeBindingList; }
            set { SetProperty(ref _employeeBindingList, value); }
        }

        /// <summary>
        /// 总页数
        /// </summary>
        private int pageCount;

        public int PageCount
        {
            get { return pageCount; }
            set { SetProperty(ref pageCount, value); }
        }

        /// <summary>
        /// 分页函数
        /// </summary>
        private void Pager()
        {
            // 当前页的起始记录位置
            this.StartPos = (this.CurrentPage - 1) * this.PageCountList[this.CurrentIndex] + 1;
            // 当前页的结束记录位置
            this.EndPos = this.CurrentPage * this.PageCountList[this.CurrentIndex];
            refresh();
        }

        private void refresh(string name = "1")
        {
            InitPage(name);
            // 修改前台绑定列表的数据
            this.EmployeeBindingList = new ObservableCollection<CollectData>();
            foreach (var item in this.StressListAll.Take(this.CurrentPage * this.PageCountList[this.CurrentIndex]).
                Skip((this.CurrentPage - 1) * this.PageCountList[this.CurrentIndex]).ToList())
            {
                EmployeeBindingList.Add(item);
            }
        }
    }
}